package com.bop.dehong;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import cn.jpush.android.api.JPushInterface;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.LogUtils;
import com.base.dehong.util.NetWorkUtils;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.ScreenUtil;
import com.base.dehong.util.StringUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.config.Config;
import com.bop.dehong.http.model.LoginModel;
import com.bop.dehong.info.LoginInfo;
import com.bop.dehong.lock.GesturePwdActivity;
import com.bop.dehong.main.MainActivity;
import com.umeng.analytics.MobclickAgent;

/**
 * 
 * @{# SplashActivity.java 
 * 
 *     class desc: 启动画面 (1)判断是否是首次加载应用采取读取SharedPreferences的方式
 *     (2)是，则进入GuideActivity；否，则进入MainActivity (3)3s后执2)操作
 * 
 *     <p>
 *     Copyright: Copyright(c) 2013
 *     </p>
 * @Version 1.0
 * @Author <a href="mailto:gaolei_xj@163.com">Leo</a>
 * 
 * 
 */
public class SplashActivity extends BaseActivity {
	private boolean testModel = true;//打包之前一定要设置这个为false
	boolean isNoFirstIn = false;
	private Activity mActivity;
	private LoginModel mLoginModel;
	private String mUsername;
	private String mPassword;
	private final int REQUEST_GUIDE = 100;
	private Long local;
	private final int REQUEST_PWD = 101;//手势密码
	private final int REQUEST_TEST = 102;//选择测试线正式线
	
	public void login(String username,  String password){
		if (mLoginModel == null) {
			mLoginModel = new LoginModel(this, loginCallBack);
		}
		String device_code = "";
//		DeviceUuidFactory factory = new DeviceUuidFactory(this);
//		device_code = factory.getDeviceUuid() + "";
		device_code = JPushInterface.getRegistrationID(this);//传RegistrationID方便后台根据指定RegistrationID推送消息
		LogUtils.e(TAG + ",device_code", "registrationId=" + device_code);
		local = System.currentTimeMillis() / 1000;
		mLoginModel.doNet(username, password, device_code);
	}
	
	RequestCallBack<LoginInfo> loginCallBack = new RequestCallBack<LoginInfo>() {

		@Override
		public void end() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onSuccess(LoginInfo info) {
			Long net = info.stamp;
			Long modify = net - local;
			if (Math.abs(modify) >= 300) {
				PreferencesUtils.putLong(SplashActivity.this, Config.TAG, modify);	
			}
			DeHongApp.mLoginEntity = info.user;
			PreferencesUtils.putString(SplashActivity.this, Config.USERNAME,
					mUsername);
			PreferencesUtils.putString(SplashActivity.this, Config.PASSWORD,
					mPassword);
			LogUtils.e(TAG + "login-entity", "login-entity=" + info.user);
			Long exitTime = PreferencesUtils.getLong(SplashActivity.this, "gesturetime");
			LogUtils.e("app上次退出时间： " + exitTime);
			Long currentTime  = System.currentTimeMillis() / 1000;
			LogUtils.e("当前时间： " + currentTime);
//			removeHeadCache();
			if (currentTime - exitTime > Config.TIMT_PSW) {
				goIntent();
			}else {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						go2Main();
					}
				}, 1000);
			}
			super.onSuccess(info);
		}

		
		
		@Override
		public void onFailure() {
			Long exitTime = PreferencesUtils.getLong(SplashActivity.this, "gesturetime");
			LogUtils.e("app上次退出时间： " + exitTime);
			Long currentTime  = System.currentTimeMillis() / 1000;
			LogUtils.e("当前时间： " + currentTime);
			if (currentTime - exitTime > 60) {
				goIntent();
			}else {
				go2Main();
			}
		}
	};
	
	
	private void goGuide() {
		Intent intent = new Intent(this,GuideActivity.class);
		startActivityForResult(intent, REQUEST_GUIDE);
	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			if (requestCode == REQUEST_PWD){
				finishCurrentActivity();
			}
			return;
		}
		if (requestCode == REQUEST_GUIDE) {//引导页
			go2Main();
		}else if (requestCode == REQUEST_PWD) {//手势密码
			go2Main();
		}else if (requestCode == REQUEST_TEST){
			LogUtils.e(TAG + ",ip", "ip=" + Config.IP);
			judge2go();
		}
	}
	
	private void go2Main(){
		openActivity(MainActivity.class);
		finishCurrentActivity();
	}
	
//	 @Override
//	 public boolean onKeyDown(int keyCode, KeyEvent event)
//	 {
//	     if (keyCode == KeyEvent.KEYCODE_BACK)
//	      {
//	            return true;
//	      }
//	      return super.onKeyDown(keyCode, event);
//	 }

	@Override
	protected void initTop() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void initUI() {
		ScreenUtil.init(this);//初始化获取屏幕参数
		MobclickAgent.openActivityDurationTrack(false);//应用程序添加友盟统计时，含Fragment需要在入口Activity中调用此方法
	}

	@Override
	protected void initData() {
		if (testModel) {
			Intent intent = new Intent(this,ChooseIPdAct.class);
			startActivityForResult(intent, REQUEST_TEST);
		}else {
			judge2go();	
		}
		
	}


	private void judge2go()
	{
		mActivity = this;
		isNoFirstIn = PreferencesUtils.getBoolean(
				SplashActivity.this, Config.isNoFirstIn);
			// 判断程序与第几次运行，如果是第一次运行则跳转到引导界面，否则跳转到主界面
			if (isNoFirstIn) {
				// 使用Handler的postDelayed方法,秒后执行跳转到MainActivity
				if (NetWorkUtils.isConnect(mActivity)) {// 有网络
					// 判断用户是否已经退出登录以获取存储的用户名和密码
						mUsername = PreferencesUtils.getString(mActivity,
								Config.USERNAME);
						mPassword = PreferencesUtils.getString(mActivity,
								Config.PASSWORD);
						if (StringUtils.isNotEmpty(mUsername)
								&& StringUtils.isNotEmpty(mPassword)) {
							login(mUsername, mPassword);// 取得保存的账号密码自动登陆	
						}
						else{
							new Handler().postDelayed(new Runnable() {
								@Override
								public void run() {
									go2Main();
								}
							}, 1000);//延迟进入首页
						}
				} else {// 无网络,提示进行网络设置
					ToastUtils.show(SplashActivity.this, "网络未打开");
					new Handler().postDelayed(new Runnable() {
						@Override
						public void run() {
							go2Main();
						}
					}, 1000);
				}
			} else {
				new Handler().postDelayed(new Runnable() {
					@Override
					public void run() {
						goGuide();
					}
				}, 1000);//延迟进入引导页
			}
	}
	
	
	/*
	 * 跳转到手势输入页
	 */
	private void goIntent() {
			Intent intent = new Intent(this, GesturePwdActivity.class);
			int type = 0;
			//如果这个人有账户和密码存在，检查一下是否有手势密码，没有则设置
			String GESTURE_PWD = PreferencesUtils.getString(this, Config.GESTURE_PWD+mUsername);//注意手势密码要加上人名
			if (TextUtils.isEmpty(GESTURE_PWD)) {
				type = 1;
			}else {
				type = 0;
			}
			intent.putExtra(Config.GO_BACK, true);
			intent.putExtra(Config.GESTURE_ACTION, type);
			startActivityForResult(intent, REQUEST_PWD);
	}
	
	@Override
	public void showNetErrorDialog() {
//		super.showNetErrorDialog();//启动页没有必要显示网络不可用
	}

	@Override
	protected int getContentViewId() {
 		TAG = getClass().getName();
		return R.layout.splash;
	}

	@Override
	protected void onResume() {
		super.onResume();
		JPushInterface.onResume(this);
	}

	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		JPushInterface.onPause(this);
	}


	@Override
	public void onClick(View v)
	{
		// TODO Auto-generated method stub
		
	}


	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
}
